<?php

require_once('./modules/log.inc');
require_once('./modules/util.inc');

class LoginRenderer extends Renderer
{
	function pageLoad()
	{
		switch( $this->action )
		{
			case "login":
				$this->doLogin();
				break;
			case "":
			case "show":
			default:
				break;
		}
	}
	
	function doLogin()
	{
		$username = $_POST['txtUsername'];
		$pwd = $_POST['txtPassword'];
		
		$user = new User();
		if( !$user->load($username))
		{
			Log::getInstance()->write("failed loading user".$username,C_LOG_INFO);
			header("Location: index.php?pg=login&act=failed");
		}
		
		if($user->checkPassword($pwd))
		{
			if(!$user->activated)
			{
				header("Location: index.php?pg=login&act=pending");
			}
			else
			{
				$_SESSION["user"] = serialize($user);
				header("Location: index.php?pg=default");
			}
		}
		else
			header("Location: index.php?pg=login&act=failed");
	}
	
	function renderContent()
	{
		global $content;
		global $siteName;
		global $G_HOME;
		
		$content = 
		"<div class='headerPitch'>
			<p><h1>Login to ".$siteName."</h1></p>
		</div>
		<div class='pageContentTitle'>
			<p></p>
		</div>
		<div class='pageContent'>
			<p>
			<form method='POST' action='".Util::combinePath($G_HOME,"index.php?pg=login&act=login")."'>
			<fieldset style='width:440px;padding:20px;'>
				<legend>Please provide your credentials:</legend>
				<label class=\"fieldTitle mandatory\">username:</label><input class='text' type='text' name='txtUsername' id='txtUsername' size='30'><br />
				<label class=\"fieldTitle mandatory\">password:</label><input class='text' type='password' name='txtPassword' id='txtPassword' size='30' /><br />
				<input type='submit' value='submit'/>";
		
		if( $this->action == "failed" )
			$content .= "<label colspan='2' style='color:red;'>Bad username or password</label>";
		else if($this->action == "pending" )
			$content .= "<label colspan='2' style='color:red;'>User pending activation.</label>";
		
		$content .= "</fieldset>
			</form>
			</p>
		</div>";
	}

	function renderLoginBox()
	{
		global $loginBox;
		global $G_HOME;
		
		$loginBox = "<div class='loginLine'>
						<ul>";
		if( isset($this->user) )
		{
			$loginBox .= "<li class='signIn'>".$this->user->screenName."</li>
				<li><a rel='nofollow' href='./?pg=logout'>sign out</a></li>";
		}
		else if($this->config->get("./features/registration/@enabled") == "1")
		{
				$loginBox .="<li class='register'><a rel='nofollow' href='".Util::combinePath($G_HOME,"?pg=register")."'>register</a></li>";
		}

		$loginBox .="	</ul>
					</div>";
	}
}

$renderer = new LoginRenderer();

?>